<template>
  <div :class="ns.b()">
    <!--<div class="content" v-spin="loadingFull ? {target: '.page-content-table'} : false">-->
    <!--</div> -->
    <div >
      <left-tab v-if="indicatorData?.length" :title="showTitleName[marketCode]" :indicatorData="arrSort(indicatorData, 'code')"
                :codeLevel2="queryData.dimensionCode" @clickLeftTab="clickLeftTab" icon="vi-hangyehuanjingjixiao"></left-tab>
    </div>
    <div class="content-right ">
      <div class="page-title">{{ indicatorName }}</div>
      <div class="page-content">
        <div class="page-content-screen">
          <div class="screen">
            <vc-filter :menus="marketCode === 'ag' ? screen : screenHg"/>
          </div>
          <div class="total">
            <span>溯源</span>
            <el-switch
              v-model="isTraceSource"
              class="ml-2"
              size="small"
              style="--el-switch-on-color: #02C680;"
            />
            <span>共计<sapn style="color: rgba(255, 89, 89, 1)">&nbsp;{{ totalNum }}&nbsp;</sapn>条</span></div>
        </div>
        <div class="page-content-table">
          <vc-table
            
            :loading="loading"
            :tableData="tableData"
            :columns="columns"
            :total="totalNum"
            :pageSize="PAGE_SIZE"
            :pageNum="queryData.pageNum"
            :defaultSort="{field:'indicator0',order:'desc'}"
            :maxHeight="maxHeight"
            @page-change="handleCurrentChange"
            @sort-change="sortChange"
          />
        </div>
      </div>
    </div>
  </div>
  <!-- 溯源弹窗 -->
  <indicator-source v-model:show="showActionsheet" :actionData="actionSheetData"/>
</template>

<script lang="ts" setup>
import { isArray } from '@vc/utils';
import {useNamespace} from "vc/src/use";
import {getEsg} from '../apis';
import {useTable} from '@/utils/esgUseTable';
import {useScreen} from './useScreen';
import {calculateTableMaxHeight} from "@/utils";
import IndicatorSource from '@/components/indicator-source/index.vue';
import leftTab from './../components/left-tab.vue'
import {useTabs} from "vc";

const {setTitle, getTitle} = useTabs();
const ns = /* hoist-static*/ useNamespace('esgIndustry');
defineOptions({name: ns.b()});
const showTitleName = {
  'ag': 'A股行业环境绩效',
  'hg': '港股行业环境绩效',
}
let needShowTable = ref(false);
let indicatorName = ref('')
const route = useRoute();
const marketCode: any = route.params.type || 'ag';
const codeLevel2: any = route.params.code;
setTitle(showTitleName[marketCode])
const {
  PAGE_SIZE,
  screen,
  screenHg,
  queryData,
  indicatorData,
  runGetYear,
  changeIndicator
} = useScreen(marketCode, codeLevel2);
let maxHeight = $ref(0)
queryData.marketCode = marketCode

interface sortRule {
  field?: string;
  order?: string
}


/** 是否溯源 */
let isTraceSource = ref(false)
/** 数量统计 */
const totalNum = ref(0);
/** 表格数据 */
const tableData = ref([]);
/** 接口数据 */
let resData = $ref();
const isPageChange = ref(false);
const loading = ref(true)
const loadingFull = ref(false)

/** 换页 */
const handleCurrentChange = (val: number) => {
  queryData.pageNum = val;
  isPageChange.value = true;
  run(queryData)
};

/** 指标排序 */
const sortChange = (event: any) => {
  const {column, order} = event;
  const {sortBy, field} = column;
  queryData.pageNum = 1;
  queryData.indicatorFiled = order ? `${sortBy || field}` : '';
  queryData.indicatorOrder = order ? order : '';
};


//点击左侧指标tab
const clickLeftTab = (item, index) => {
  if (item.code != queryData.dimensionCode) {
    needShowTable.value = false;
    runGetYear({
      dimensionCode: 3,
      codeLevel2: item.code
    })
    queryData.indicatorFiled = '';
    queryData.indicatorOrder = '';
    queryData.indicatorCodes = '';
    indicatorName.value = item.name
    changeIndicator(index);
    loadingFull.value = true;
  }
}
const {data: esgData, run} = useRequest(getEsg, {
  manual: true,
  defaultParams: [{...queryData}],
  onSuccess(res) {
    indicatorName.value = indicatorData.value.filter((item) => item.code === queryData.dimensionCode)[0].name;
    resData = res
    totalNum.value = res.total;
    //第一行单位的数据
    let unitItem = {
      securitiesCode: '单位',
      securitiesName: ' ',
      companyId: '',
    }
    res.indicators.forEach((item, index) => {
      unitItem[`indicator${index}`] = {
        indicatorDisplayValue: item.unit
      }
    })
    let newTableData: any = [unitItem];
    res.details.forEach((item,indexP) => {
      let tableItem = {
        securitiesCode: item.performanceSecurities.securitiesCode,
        securitiesName: item.performanceSecurities.securitiesName,
        companyId: item.performanceSecurities.companyId,
      }
      item.indicatorInfo.forEach((indica, index) => {
        tableItem[`indicator${index}`] = indica
      })
      tableItem['seqIndex'] = (queryData.pageNum - 1) * PAGE_SIZE + indexP + 1;
      newTableData.push(tableItem)
    })
    if(res.details && res.details.length === 0){
      tableData.value = []
    }else{
      tableData.value = newTableData;
    }
    needShowTable.value = true
    nextTick(() => {
      loading.value = false;
      loadingFull.value = false;
      //计算最大高度
      maxHeight = calculateTableMaxHeight()
    })
  }
})
//页面resize，重新计算高度
window.onresize = function () {
  maxHeight = calculateTableMaxHeight()
}
const {columns, showActionsheet, actionSheetData} = useTable(esgData, isTraceSource);

watch(
  () => queryData,
  (val) => {
    loading.value = true
    if (!isPageChange.value) {
      queryData.pageNum = 1;
    } else {
      isPageChange.value = false;
    }
    run(val);
  },
  {deep: true}
);

function arrSort<T> (arr: T[], attr: string | Array<Numberish>, isAsc = true, deepName?: string) {
  function sortFn () {
    // 第二个参数没有传递 默认升序排列
    const _order = isAsc ? 1 : -1;
    
    return function (a, b) {
      if (!isArray(attr)) {
        attr = [attr];
      }
      for (const item of attr) {
        a = a[item] || Number.MAX_VALUE;
        b = b[item] || Number.MAX_VALUE;
      }
      if (a < b) {
        return _order * -1;
      }
      if (a > b) {
        return _order * 1;
      }
      return 0;
    };
  }
  
  arr.sort(sortFn());
  
  if (deepName) {
    for (const item of arr) {
      if (item[deepName]?.length) {
        arrSort(item[deepName], attr, isAsc, deepName);
      }
    }
  }
  
  return arr;
}
</script>
<style lang="scss" scoped>
@import "./index.scss";

.vc-esgIndustry {
  display: flex;
}

.content-right {
  width: 100%;
  overflow-x: auto;
}
</style>
